package com.example.demo.information.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.demo.common.utils.Constant;
import com.example.demo.common.utils.ImgUtils;
import com.example.demo.common.utils.PhotoOSSUtils;
import com.example.demo.common.utils.WXAIPhotoAPI;
import com.example.demo.information.entity.*;
import com.example.demo.information.entity.info.StudentInfo;
import com.example.demo.information.repository.PhotoRepository;
import com.example.demo.information.service.PhotoService;
import com.example.demo.param.entity.Param;
import com.example.demo.param.repository.ParamRepository;
import com.example.demo.param.service.ParamService;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class PhotoServiceImpl implements PhotoService {
    @Autowired
    private PhotoRepository photoRepository;
    @Autowired
    private ParamRepository paramRepository;
    @Autowired
    private ParamService paramService;

    @Override
    public List<Photo> findByXsxxIdAndStatusOrderByLrsjDesc(Long xsxxId, Integer status) {
        return photoRepository.findByXsxxIdAndStatusOrderByLrsjDesc(xsxxId,status);
    }
    /**
     * 保存照片信息
     * @param student
     * @param spId
     * @param bkColor
     * @param truePath
     * @param resultSavePath
     * @param internetPath
     * @return
     */
    @Override
    public String savePhotoByStudent(Student student, String spId, String bkColor
            , String truePath, String resultSavePath, String internetPath, String xgr) {
        Date date = new Date();
        String xgsj = Constant.formatter.get().format(date);
        //List<Photo> list = photoRepository.findByXsxxIdAndStatusOrderByLrsjDesc(student.getId(),1);
        Photo photo = photoRepository.findByXsxxIdAndXxxxIdAndBjxxId(student.getId()
                ,student.getSchool().getId(),student.getBjxx().getId());
        if(photo==null){
            photo = new Photo(student);
            photo.setLrr(xgr);
            photo.setLrsj(xgsj);
        }else{
            photo.setStatus(1);
            photo.setCreatemessage(Constant.formatter2.get().format(date)
                    +"@@@"+ student.getSchool().getName()
                    +"@@@"+ student.getBjxx().getName());
            photo.setXgr(xgr);
            photo.setXgsj(xgsj);
        }
        photo.setYtpath(truePath);
        photo.setApipath(internetPath);
        photo.setSavepath(resultSavePath);
        photo.setSpid(spId);
        photo.setBkcolor(bkColor);
        photoRepository.save(photo);
        return "success";
    }

    /**
     * 确认选择临时拍摄的证件照作为正式的证件照
     * @param tempPhoto
     * @return
     */
    @Override
    public String saveHistoryPhoto(Historyphoto tempPhoto) {
        Date date = new Date();
        String xgsj = Constant.formatter.get().format(date);
        Photo photo = photoRepository.findByXsxxIdAndXxxxIdAndBjxxId(tempPhoto.getXsxxId()
                ,tempPhoto.getXxxxId(),tempPhoto.getBjxxId());
        if(photo==null){
            photo = new Photo(tempPhoto);
        }else{
            photo.setStatus(1);
            photo.setCreatemessage(tempPhoto.getCreatemessage());
            photo.setXgr(tempPhoto.getLrr());
            photo.setXgsj(tempPhoto.getLrsj());
        }
        photo.setYtpath(tempPhoto.getYtpath());
        photo.setApipath(tempPhoto.getApipath());
        photo.setSavepath(tempPhoto.getSavepath());
        photo.setSpid(tempPhoto.getSpid());
        photo.setBkcolor(tempPhoto.getBkcolor());
        photoRepository.save(photo);
        return "success";
    }

    /**
     * 下载学生的一寸照片(证件照)
     * @param stuList
     */
    @Override
    public void downLoadStuPhoto(List<Student> stuList,HttpServletResponse response) {
        Map<Long, Map<Long,List<Photo>>> photoMap = new HashMap<>();//保存照片信息  Map<xxxxId,Map<bjxxId,List<Photo>>>
        Map<Long, School> schoolMap = new HashMap<>();
        Map<Long, Bjxx> bjxxMap = new HashMap<>();
        Map<Long,Student> studentMap = new HashMap<>();
        int count =0;
        for(Student s:stuList){
            if(s.getSchool()==null||s.getBjxx()==null){
                continue;
            }
            Photo photo = photoRepository.findByXsxxIdAndXxxxIdAndBjxxId(
                    s.getId(),s.getSchool().getId(),s.getBjxx().getId());
            if(photo!=null){
                count++;
                schoolMap.put(s.getSchool().getId(),s.getSchool());
                bjxxMap.put(s.getBjxx().getId(),s.getBjxx());
                studentMap.put(s.getId(),s);
                if(photoMap.containsKey(s.getSchool().getId())){
                    Map<Long, List<Photo>> tempBjxxMap = photoMap.get(s.getSchool().getId());
                    if(tempBjxxMap.containsKey(s.getBjxx().getId())){
                        List<Photo> list = tempBjxxMap.get(s.getBjxx().getId());
                        list.add(photo);
                    }else{
                        List<Photo> list = new ArrayList<>();
                        list.add(photo);
                        tempBjxxMap.put(s.getBjxx().getId(),list);
                    }
                }else{
                    Map<Long,List<Photo>> tempBjxxMap = new HashMap<>();
                    List<Photo> list = new ArrayList<>();
                    list.add(photo);
                    tempBjxxMap.put(s.getBjxx().getId(),list);
                    photoMap.put(s.getSchool().getId(),tempBjxxMap);
                }
            }
        }
        if(count>0){
            PhotoOSSUtils oss = new PhotoOSSUtils();
            byte[] buffer = new byte[1024];
            //生成zip文件存放位置
            String dateStr = Constant.formatter2.get().format(new Date());
            String rootPath = Constant.tempTempFolder+dateStr+"/";//压缩包文件保存的temp根目录
            String zipFileName = "学生证件照"+dateStr+".zip";
            String strZipPath = rootPath+zipFileName;
            File file=new File(rootPath);
            if(!file.isDirectory() && !file.exists()){//如果文件夹不存在,新建一个
                file.mkdirs();
            }
            try {
                ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
                List<String> fileEntitysPathArr = Lists.newArrayList();//临时文件保存地址
                // 需要同时下载的多个文件
                for(Map.Entry<Long,Map<Long,List<Photo>>> entry:photoMap.entrySet()){//学校级
                    Long xxxxId = entry.getKey();
                    School school = schoolMap.get(xxxxId);
                    Map<Long, List<Photo>> bjPhotoMap = entry.getValue();
                    //List<Param> photoNameParamList = paramService.findSchoolPhotoParam(xxxxId,Constant.PARAM_PZSM_PHOTONAME);
                    List<Param> photoNameParamList = paramService.getPhotoParam(Constant.PARAM_PZSM_PHOTONAME,xxxxId);
                    Param photoNameParam = photoNameParamList!=null&&!photoNameParamList.isEmpty()
                            ?photoNameParamList.get(0):null;
                    String nameParam = photoNameParam!=null&&StringUtils.isNotBlank(photoNameParam.getPzz())
                            ?photoNameParam.getPzz():Constant.defaultPhotoNameParam;//导出文件名格式
                    for(Map.Entry<Long,List<Photo>> entry2:bjPhotoMap.entrySet()){//班级级
                        Long bjxxId = entry2.getKey();
                        Bjxx bjxx = bjxxMap.get(bjxxId);
                        String contentPathBody = school.getName()+"/"+bjxx.getName()+"/";
                        String contentPath = rootPath + contentPathBody;//班级级下的子目录
                        File sonFile=new File(contentPath);
                        if(!sonFile.isDirectory() && !sonFile.exists()){//如果文件夹不存在,新建一个
                            sonFile.mkdirs();
                        }
                        List<Photo> photoList = entry2.getValue();
                        for(Photo photo: photoList){//学生级
                            if(photo==null||StringUtils.isBlank(photo.getSavepath())){continue;}
                            String objectName = photo.getSavepath();//证件照文件路径
                            if(!oss.checkFile(objectName)){//文件读不到
                                continue;
                            }
                            FileInputStream fin = null;
                            String fileExt = objectName.substring(objectName.lastIndexOf("."));
                            Student student = studentMap.get(photo.getXsxxId());
                            StudentInfo studentInfo = new StudentInfo(student,bjxx,school);
                            String fileName = paramService
                                    .getPhotoFileNameByStudentInfoAndPzz(studentInfo,nameParam);
                            fileName = fileName+fileExt;
                            ///TODO 可以优化下,尝试文件流?
                            oss.downFile(contentPath+fileName,objectName);
                            File fileEntity = new File(contentPath+fileName);
                            fileEntitysPathArr.add(contentPath+fileName);
                            fin = new FileInputStream(fileEntity);
                            out.putNextEntry(new ZipEntry(contentPathBody+fileName));
                            //设置压缩文件内的字符编码，不然会变成乱码
                            out.setEncoding("UTF-8");
                            //out.setEncoding("GBK");
                            int len;
                            // 读入需要下载的文件的内容，打包到zip文件
                            while ((len = fin.read(buffer)) > 0) {
                                out.write(buffer, 0, len);
                            }
                            out.closeEntry();
                            fin.close();
                        }
                    }
                }
                out.close();
                File zipFile = new File(strZipPath);
                // 写出文件到前台
                InputStream ins = new FileInputStream(zipFile);
                //  放到缓冲流里面
                BufferedInputStream bins = new BufferedInputStream(ins);
                //  获取文件输出IO流
                OutputStream outs = response.getOutputStream();
                BufferedOutputStream bouts = new BufferedOutputStream(outs);
                // 设置response内容的类型
                response.setContentType("application/x-download");
                response.setHeader("Content-disposition",
                        "attachment;filename=" + URLEncoder.encode(
                                zipFileName.substring(0,zipFileName.lastIndexOf("."))+".zip", "UTF-8"));
                int bytesRead = 0;
                byte[] buffer1 = new byte[2048];
                // 开始向网络传输文件流
                while ((bytesRead = bins.read(buffer1, 0, 2048)) > 0) {
                    bouts.write(buffer1, 0, bytesRead);
                }
                bouts.flush();
                ins.close();
                bins.close();
                outs.close();
                bouts.close();
                for(String str:fileEntitysPathArr){//删除临时保存的文件
                    deleteFile(str);
                }
                deleteFile(strZipPath);
                deleteFolder(rootPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 下载对应photo照片对象
     * @param fileName 文件命名
     * @param photo
     * @param type
     * @param response
     */
    @Override
    public void downLoadStuPhotoOwn(String fileName ,Photo photo, String type, HttpServletResponse response) {
        if(photo==null){return;}
        List<String> filePathList = new ArrayList<>();
        switch (type){
            case(Constant.typePhotoOri) :
                if(StringUtils.isNotBlank(photo.getYtpath())){filePathList.add(photo.getYtpath());}
                break;
            case(Constant.typePhotoPas) :
                if(StringUtils.isNotBlank(photo.getSavepath())){filePathList.add(photo.getSavepath());}
                break;
            case(Constant.typePhotoAll) :
            default:
                if(StringUtils.isNotBlank(photo.getSavepath())){filePathList.add(photo.getSavepath());}
                if(StringUtils.isNotBlank(photo.getYtpath())){filePathList.add(photo.getYtpath());}
        }
        if(filePathList==null||filePathList.isEmpty()){return;}
        PhotoOSSUtils oss = new PhotoOSSUtils();
        if(filePathList.size()>1){
            //TODO 当前是采用服务器下载后再打包给客户端的方式
            Date date = new Date();
            String tempParentFolder = Constant.tempTempFolder+Constant.formatter2.get().format(date)+"@OBJ"+"/";
            List<String> localPathList = oss.downObjectNameListToLocalList(tempParentFolder,filePathList);
            //打包下载
            photoFileZip(fileName,localPathList,response);
            try {
                for(String str :localPathList){
                    deleteFile(str);
                }
                deleteFolder(tempParentFolder);
            } catch (IOException e) {
                e.printStackTrace();
                log.warn("文件夹或者文件删除失败,文件目录:"+tempParentFolder);
            }
        }else{
            try{
                oss.downObjectName(filePathList.get(0),fileName,response);
            } catch (IOException e) {
                e.printStackTrace();
                log.warn("文件失败,文件oss路径:"+filePathList.get(0));
            }
        }
    }

    /**
     * 学生原始招聘转化成证件照并保存原图与证件照
     * @param file  上传过来原图
     * @param studentInfo 学生信息(含班级\学校信息)
     * @param objectName 文件保存的一级目录
     * @param fileSaveName 文件保存名
     * @param date 操作的时间
     * @param localRoot 本地临时保存目录
     * @return
     */
    @Override
    public Map<String,String> stuOriginalPhotoToPassportAndSave(MultipartFile file , StudentInfo studentInfo
            , String objectName, String  fileSaveName, Date date, String localRoot) {
        Map<String,String> map = new HashMap<>();
        PhotoOSSUtils photoOSSUtils = new PhotoOSSUtils();//OSS保存方法
        String ytPhotoObjectName = photoOSSUtils.uploadStuPhotoFile(file,objectName,fileSaveName,date,localRoot);
        if(!photoOSSUtils.checkFile(ytPhotoObjectName)){
            map.put("msg","原图文件保存失败");
            return map;
        }
        String spId = Constant.defaultPhotoParamSpid;
        String bkColor = Constant.defaultPhotoParamBkColor;
        Param photoParam = null;
        if(studentInfo!=null&&studentInfo.getXxxxId()!=null){
            List<Param> photoParamList = paramRepository.findByXxxxIdAndPzsm(studentInfo.getXxxxId(),Constant.PARAM_PZSM_PHOTO);
            photoParam = photoParamList!=null&&!photoParamList.isEmpty()?photoParamList.get(0):null;
        }

        if(photoParam==null){
            List<Param> photoParamList = paramRepository.findByPzsmAndXxxxIdNull(Constant.PARAM_PZSM_PHOTO);
            photoParam = photoParamList!=null&&!photoParamList.isEmpty()?photoParamList.get(0):null;
        }
        if(photoParam!=null){
            spId = photoParam.getPzz();
            bkColor = photoParam.getPzz2();
        }
        String resultSavePath = ytPhotoObjectName.substring(0,ytPhotoObjectName.lastIndexOf("."))
                + "@@"+spId+"@@"+bkColor
                + ytPhotoObjectName.substring(ytPhotoObjectName.lastIndexOf("."));
        String resultSaveObjectName = resultSavePath;
        String tempResultSavePath = localRoot+resultSavePath;
        String tempYtPhotoPath = localRoot+ytPhotoObjectName;
        WXAIPhotoAPI api = new WXAIPhotoAPI();
        String result = api.usePhotoAPI(tempYtPhotoPath, spId, bkColor, tempResultSavePath);
        String internetPath = api.extractValueFromJsonString(result, "result");
        String status = api.extractValueFromJsonString(result, "status");

        System.out.println("ytPhotoObjectName:"+ytPhotoObjectName);
        System.out.println("resultSaveObjectName"+resultSaveObjectName);
        System.out.println("tempResultSavePath:"+tempResultSavePath);
        System.out.println("InternetPath:"+internetPath);
        System.out.println("status:"+status);

        map.put("spId",spId);
        map.put("bkColor",bkColor);
        map.put("ytPhotoObjectName",ytPhotoObjectName);
        map.put("resultSaveObjectName",resultSaveObjectName);
        map.put("internetPath",internetPath);

        if (!"0".equals(status)) {
            System.out.println("bad status:" + status);
            map.put("msg","证件照生成失败,请联系管理员.");
            return map;
        }
        //结果照片上传到oss
        photoOSSUtils.uploadStuPhotoByLocalPath(tempResultSavePath,resultSaveObjectName);
        if(!photoOSSUtils.checkFile(resultSaveObjectName)){
            map.put("msg","证件照文件保存失败");
            return map;
        }
        //把临时保存的文件给删除
        deleteFile(tempYtPhotoPath);
        try{
            deleteFolder(localRoot);
        } catch (IOException e) {
            e.printStackTrace();
            log.warn("文件夹或者文件删除失败,文件目录:"+localRoot);
        }
        map.put("msg",Constant.SUCCESS);
        return map;
    }

    /**
     * 学生证件照上传并保存证件照
     * @param file  上传过来文件
     * @param studentInfo 学生信息(含班级\学校信息)
     * @param objectName 文件保存的一级目录
     * @param fileSaveName 文件保存名
     * @param date 操作的时间
     * @param localRoot 本地临时保存目录
     * @param spId 由于是自己上传文件的，需要输入下证件照类型
     * @param bkColor 由于是自己上传文件的，需要输入下证件照类型
     * @return
     */
    @Override
    public Map<String, String> stuPassportAndSave(MultipartFile file, StudentInfo studentInfo
            , String objectName, String fileSaveName, Date date, String localRoot, String spId, String bkColor) {
        Map<String,String> map = new HashMap<>();
        PhotoOSSUtils photoOSSUtils = new PhotoOSSUtils();//OSS保存方法
        spId = StringUtils.isBlank(spId)?Constant.defaultPhotoParamSpid:spId;
        bkColor = StringUtils.isBlank(bkColor)?Constant.defaultPhotoParamBkColor:bkColor;
        String resultSaveObjectName = photoOSSUtils.uploadStuPhotoFile(file,objectName,fileSaveName,date,localRoot);
        if(!photoOSSUtils.checkFile(resultSaveObjectName)){
            map.put("msg","证件照文件保存失败");
            return map;
        }
        String tempResultSavePath = localRoot+resultSaveObjectName;

        map.put("spId",spId);
        map.put("bkColor",bkColor);
        map.put("ytPhotoObjectName",null);
        map.put("resultSaveObjectName",resultSaveObjectName);
        map.put("internetPath",null);

        //把临时保存的文件给删除
        deleteFile(tempResultSavePath);
        try{
            deleteFolder(localRoot);
        } catch (IOException e) {
            e.printStackTrace();
            log.warn("文件夹或者文件删除失败,文件目录:"+localRoot);
        }
        map.put("msg",Constant.SUCCESS);
        return map;
    }

    /**
     * 学生原照上传并保存原照
     * @param file  上传过来文件
     * @param studentInfo 学生信息(含班级\学校信息)
     * @param objectName 文件保存的一级目录
     * @param fileSaveName 文件保存名
     * @param date 操作的时间
     * @param localRoot 本地临时保存目录
     * 学生原照上传并保存原照
     * @return
     */
    @Override
    public Map<String,String> stuOriginalPhotoAndSave(MultipartFile file, StudentInfo studentInfo
                , String objectName, String fileSaveName, Date date, String localRoot) {
        Map<String,String> map = new HashMap<>();
        PhotoOSSUtils photoOSSUtils = new PhotoOSSUtils();//OSS保存方法
        String originalSaveObjectName = photoOSSUtils.uploadStuPhotoFile(file,objectName,fileSaveName,date,localRoot);
        if(!photoOSSUtils.checkFile(originalSaveObjectName)){
            map.put("msg","证件照文件保存失败");
            return map;
        }
        map.put("spId","");
        map.put("bkColor","");
        map.put("ytPhotoObjectName",originalSaveObjectName);
        map.put("resultSaveObjectName", null);
        map.put("internetPath",null);

        //把临时保存的文件给删除
        String tempOriginalSavePath = localRoot+originalSaveObjectName;
        deleteFile(tempOriginalSavePath);
        try{
            deleteFolder(localRoot);
        } catch (IOException e) {
            e.printStackTrace();
            log.warn("文件夹或者文件删除失败,文件目录:"+localRoot);
        }
        map.put("msg",Constant.SUCCESS);
        return map;
    }

    /**
     * 将原图重新转化成证件照
     * @param studentInfo 学生信息
     * @param ytPhotoObjectName 原图的objectName  oss地址
     * @param date 操作的时间
     * @param localRoot 本地保存的临时文件夹
     * @return
     */
    @Override
    public Map<String,String> tranformOriginal(StudentInfo studentInfo, String ytPhotoObjectName, Date date, String localRoot) {
        Map<String,String> map = new HashMap<>();
        PhotoOSSUtils photoOSSUtils = new PhotoOSSUtils();//OSS保存方法
        if(!photoOSSUtils.checkFile(ytPhotoObjectName)){
            map.put("msg","原图不存在");
            return map;
        }
        //原图要先下载到本地
        String tempYtPhotoPath = localRoot+ytPhotoObjectName;
        photoOSSUtils.downFile(tempYtPhotoPath,ytPhotoObjectName);
        File jpegFile = new File(tempYtPhotoPath);
        String rotateMsg = ImgUtils.rotateImgByExif(jpegFile);
        System.out.println("PhotoServiceImpl-tranformOriginal-rotateMsg:"+rotateMsg);
        if(!Constant.SUCCESS.equals(rotateMsg)){
            map.put("msg","原图读取出错,原因："+rotateMsg);
            return map;
        }

        if(!checkLocalFile(tempYtPhotoPath)){
            map.put("msg","原图转化过程出错,原因：原图未找到");
            return map;
        }
        String spId = Constant.defaultPhotoParamSpid;
        String bkColor = Constant.defaultPhotoParamBkColor;
        Param photoParam = null;
        if(studentInfo!=null&&studentInfo.getXxxxId()!=null){
            List<Param> photoParamList = paramRepository.findByXxxxIdAndPzsm(studentInfo.getXxxxId(),Constant.PARAM_PZSM_PHOTO);
            photoParam = photoParamList!=null&&!photoParamList.isEmpty()?photoParamList.get(0):null;
        };
        if(photoParam==null){
            List<Param> photoParamList = paramRepository.findByPzsmAndXxxxIdNull(Constant.PARAM_PZSM_PHOTO);
            photoParam = photoParamList!=null&&!photoParamList.isEmpty()?photoParamList.get(0):null;
        }
        if(photoParam!=null){
            spId = photoParam.getPzz();
            bkColor = photoParam.getPzz2();
        }
        String resultSaveObjectName = ytPhotoObjectName.substring(0,ytPhotoObjectName.lastIndexOf("."))
                + "@@"+spId+"@@"+bkColor
                + ytPhotoObjectName.substring(ytPhotoObjectName.lastIndexOf("."));
        String tempResultSavePath = localRoot+resultSaveObjectName;
        WXAIPhotoAPI api = new WXAIPhotoAPI();
        String result = api.usePhotoAPI(tempYtPhotoPath, spId, bkColor, tempResultSavePath);
        String internetPath = api.extractValueFromJsonString(result, "result");
        String status = api.extractValueFromJsonString(result, "status");
        String error = api.extractValueFromJsonString(result, "error");

        map.put("spId",spId);
        map.put("bkColor",bkColor);
        map.put("ytPhotoObjectName",ytPhotoObjectName);
        map.put("resultSaveObjectName",resultSaveObjectName);
        map.put("internetPath",internetPath);
        System.out.println("status========="+status);
       /* if (!"0".equals(status)) {
            map.put("msg","证件照生成失败,请联系管理员.");
            return map;
        }*/
        System.out.println("error========="+error);
        if (StringUtils.isNotBlank(error)) {
            map.put("msg","证件照生成失败,错误信息："+error);
            return map;
        }
        //结果照片上传到oss
        photoOSSUtils.uploadStuPhotoByLocalPath(tempResultSavePath,resultSaveObjectName);
        if(!photoOSSUtils.checkFile(resultSaveObjectName)){
            map.put("msg","证件照文件保存失败");
            return map;
        }
        //把临时保存的文件给删除
        deleteFile(tempYtPhotoPath);
        try{
            deleteFolder(localRoot);
        } catch (IOException e) {
            e.printStackTrace();
            log.warn("文件夹或者文件删除失败,文件目录:"+localRoot);
        }
        map.put("msg",Constant.SUCCESS);
        return map;
    }

    /**
     * 检查本地的文件是否存在
     * @param filePath 本地的绝对路径
     * @return false 不存在 ; true 存在
     */
    private boolean checkLocalFile(String filePath){
        File file = new File(filePath);
        return file.exists()?true:false;
    }

    /**
     * 删除文件
     * @param filePath
     */
    private void deleteFile(String filePath){
        File temp=new File(filePath);//删除文件
        if(temp.exists()){
            temp.delete();
        }
    }
    /**
     * 删除目录
     * @param folder
     * @throws IOException
     */
    private void deleteFolder(String folder) throws IOException {
        File temp2=new File(folder);//删除文件夹地址
        if(temp2.exists()){
            FileUtils.deleteDirectory(temp2);
        }
    }

    /**
     * 用于文件打包下载(本地文件打包)
     * @param fileName     压缩包文件以及里面的文件名
     * @param filePathList 文件路径List
     * @param response
     */
    private void photoFileZip(String fileName, List<String> filePathList, HttpServletResponse response){
        Set<String> fileNameSet = new HashSet<>();//用于校验是否有重名的文件
        int count = 2;//用于重名时添加
        byte[] buffer = new byte[1024];
        //生成zip文件存放位置
        String dateStr = Constant.formatter2.get().format(new Date());
        String rootPath = Constant.tempTempFolder+dateStr+"/";//文件保存的temp根目录
        String zipFileName = fileName+"_"+dateStr+".zip";
        String strZipPath = rootPath+zipFileName;
        File file=new File(rootPath);
        if(!file.isDirectory() && !file.exists()){//如果文件夹不存在,新建一个
            file.mkdirs();
        }
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
            List<String> fileEntitysPathArr = Lists.newArrayList();//临时文件保存地址
            // 需要同时下载的多个文件
            for(String photoPath:filePathList){
                File fileTemp = new File(photoPath);
                if(!fileTemp.exists()){//文件读不到
                    continue;
                }
                FileInputStream fin = null;
                String fileExt = photoPath.substring(photoPath.lastIndexOf("."));
                String childFileName = fileName;
                if(fileNameSet.contains(fileName)){
                    childFileName = fileName+"_"+count;
                    count++;
                }
                fileNameSet.add(childFileName);
                childFileName = childFileName+fileExt;
                File fileEntity = new File(childFileName);
                fileEntitysPathArr.add(childFileName);
                Files.copy(fileTemp, fileEntity);
                fin = new FileInputStream(fileTemp);
                out.putNextEntry(new ZipEntry(childFileName));
                //设置压缩文件内的字符编码，不然会变成乱码
                out.setEncoding("UTF-8");
                //out.setEncoding("GBK");
                int len;
                // 读入需要下载的文件的内容，打包到zip文件
                while ((len = fin.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.closeEntry();
                fin.close();
            }
            out.close();
            File zipFile = new File(strZipPath);
            // 写出文件到前台
            InputStream ins = new FileInputStream(zipFile);
            //  放到缓冲流里面
            BufferedInputStream bins = new BufferedInputStream(ins);
            //  获取文件输出IO流
            OutputStream outs = response.getOutputStream();
            BufferedOutputStream bouts = new BufferedOutputStream(outs);
            // 设置response内容的类型
            response.setContentType("application/x-download");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + URLEncoder.encode(
                            zipFileName.substring(0,zipFileName.lastIndexOf("."))+".zip", "UTF-8"));
            int bytesRead = 0;
            byte[] buffer1 = new byte[2048];
            // 开始向网络传输文件流
            while ((bytesRead = bins.read(buffer1, 0, 2048)) > 0) {
                bouts.write(buffer1, 0, bytesRead);
            }
            bouts.flush();
            ins.close();
            bins.close();
            outs.close();
            bouts.close();
            for(String str:fileEntitysPathArr){//删除临时保存的文件
                deleteFile(str);
            }
            deleteFile(strZipPath);//删除临时保存的压缩包
            try{
                deleteFolder(rootPath);//删除临时保存的文件夹地址
            } catch (IOException e) {
                e.printStackTrace();
                log.warn("文件夹或者文件删除失败,文件目录:"+rootPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Photo findByXsxxIdAndXxxxIdAndBjxxId(Long xsxxId, Long xxxxId, Long bjxxId) {
        return photoRepository.findByXsxxIdAndXxxxIdAndBjxxId(xsxxId,xxxxId,bjxxId);
    }

    @Override
    public Photo findById(Long id) {
        return photoRepository.findById(id).get();
    }


}
